package org.petstore.service.impl;

import org.petstore.domain.Item;
import org.petstore.persistence.ShoppingCartDAO;
import org.petstore.persistence.impl.ShoppingCartDAOImpl;
import org.petstore.service.CatalogService;
import org.petstore.service.CartService;
import org.petstore.util.Cart;
import org.petstore.util.CartItem;

import java.util.List;

public class CartServiceImpl implements CartService {
    ShoppingCartDAO shoppingCartDAO;
    CatalogService catalogService;

    public CartServiceImpl() {
    }

    public CartServiceImpl(ShoppingCartDAO shoppingCartDAO, CatalogService catalogService) {
        this.shoppingCartDAO = shoppingCartDAO;
        this.catalogService = catalogService;
    }

    /**
     * description 获取购物车
     *
     * @param username:
     * @return Cart
     * @author huangzhangyan
     * @date 2022/1/10 15:25
     */
    @Override
    public Cart getCartByName(String username) {
        //通过该类的私有方法 获取所有的购物车物品
        List<CartItem> cartItemList = this.getCartListByName(username);
        return new Cart(cartItemList);
    }


    /**
     * description 添加一个CartItem进购物车
     *
     * @param username:
     * @param cartItem:
     * @author huangzhangyan
     * @date 2022/1/10 15:25
     */
    @Override
    public void addIntoCart(String username, CartItem cartItem) {
        List<CartItem> list = this.getCartListByName(username);

        //局部代码块(普通代码块):控制变量的生命周期,提高内存利用率
        {
            //临时变量
            Cart tmpCart = new Cart(list);
            tmpCart.addCartItem(cartItem);
            list = tmpCart.getCartItemList();
        }

        //tmpCart在这里会报错
        shoppingCartDAO.store(username, list);
    }

    /**
     * description 删除一个在购物车
     * `@param username:
     *
     * @param itemId: `
     * @author huangzhangyan
     * @date 2022/1/10 15:25
     */
    @Override
    public void deleteInCart(String username, String itemId) {
        //根据itemId获取Item
        Item item = catalogService.getItem(itemId);

        //
        List<CartItem> list = this.getCartListByName(username);
        {
            //临时变量
            Cart tmpCart = new Cart(list);
            CartItem cartItem = new CartItem();
            cartItem.setItem(item);
            tmpCart.addCartItemIgnoreQuantity(cartItem);
            list = tmpCart.getCartItemList();
        }

        shoppingCartDAO.store(username, list);
    }


    //以下为impl的私有方法 不想被其他类调用

    /**
     * description 获取用户下的所有的购物车物品
     *
     * @param username:
     * @return List<CartItem>
     * @author huangzhangyan
     * @date 2022/1/10 15:26
     */
    private List<CartItem> getCartListByName(String username) {
        return shoppingCartDAO.getCartList(username);
    }

}
